import { useEffect } from "react";
import { useBoolean } from "ahooks";
import Taro, { useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";

import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import ByTag from "@/components/ui/ByTag";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import Card from "@/components/common/Card";
import Moment from "@/components/app/Moment";
import ByEmpty from "@/components/ui/ByEmpty";
import Divider from "@/components/app/Divider";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import ByImageGroup from "@/components/ui/ByImageGroup";
import PopupExtension from "./components/PopupExtension";
import PopupCompleted from "./components/PopupCompleted";

import useFetch from "@/hooks/useFetch";
import ApiCrm from "@/api/crm";

import { ConstructionPlanDetail } from "@/types/construction";
import { IntentCustomerData } from "@/types/customer";
import ApiApp from "@/api/app";
import setting from "@/utils/setting";

// extensionState: 0 | 1提交 | 2已审批（通过） | -1驳回

const enumExtensionState = {
  1: { label: "待审批", type: "primary" },
  2: { label: "已通过", type: "success" },
  "-1": { label: "已驳回", type: "error" },
};

// 延期申请记录卡片
const ExtensionRecordCard = ({ item }) => {
  const { extensionState, extensionPicList } = item;
  const tagConfig = enumExtensionState[extensionState];

  return (
    <>
      <ByCell
        label="延期类型"
        size="small"
        nextIcon={
          tagConfig && (
            <ByTag size="small" type={tagConfig.type}>
              {tagConfig.label}
            </ByTag>
          )
        }
      >
        {item.extensionType}
      </ByCell>
      <ByCell label="延期天数" size="small">
        {item.extensionDate}天
      </ByCell>
      <ByCell label="延期原因" size="small">
        {item.extensionReason || "--"}
      </ByCell>
      {extensionPicList?.length > 0 && (
        <ByCell label="图片" size="small" vertical>
          <ByImageGroup urls={extensionPicList.map((e) => e.picture)} />
        </ByCell>
      )}
    </>
  );
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);
  const constructionPlanId = Number(params.constructionPlanId);



  // 延期弹窗
  const [visibleExtension, handleExtension] = useBoolean();
  // 完工弹窗
  const [visibleCompleted, handleComplete] = useBoolean();


  const { data: isSwitch } = useFetch<{ switch: boolean }>(ApiCrm.controlSwitch, "POST")

  // 客户信息
  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res: any) => res.intentCustomer,
  });

  // 获取施工详情（有数据状态）
  const { data: constructionDetail, refresh } = useFetch<
    ConstructionPlanDetail & {
      formConstructionPlanExtensionList: any[];
    }
  >(ApiCrm.getPlanDetail, "POST", {
    defaultParams: [
      {
        constructionPlanId,
        workerDistributeIds: params.workerids?.split(",").map(Number),
      },
    ],
    onAfter: (res: any) => res.constructionPlanDetail,
    onSuccess(res) {
      Taro.setNavigationBarTitle({ title: res.constructionProjectName });
    },
  });

  useEffect(() => {
    handleComplete.setFalse();
    handleExtension.setFalse();
  }, [constructionDetail]);

  // 延期列表
  const extensionList =
    constructionDetail?.formConstructionPlanExtensionList || [];

  // 是否延期
  const isExtension = !!constructionDetail?.extensionDate;

  // 延期审批状态： 审核中
  // const isPending = extensionList.at(-1)?.

  // 施工状态
  const planState =
    constructionDetail?.completeState == 88
      ? "complate"
      : constructionDetail?.startState == 1
        ? "started"
        : "unstarted";

  // 获取最后条延期记录信息状态
  const extensionState = extensionList.at(-1)?.extensionState;
  // 当前施工是否存在延期 审批状态,若有，就隐藏延期按钮
  const isExtensionPending = extensionState === 1;

  // 获取H5ID签名
  const { loading, run: getEncryptId } = useFetch(ApiApp.getEncryptId, {
    manual: true,
    async onSuccess(res: any) {
      const { confirm } = await Taro.showModal({
        title: "复制分享链接",
        content: "链接有效期3天，可将地址粘贴给客户",
        confirmText: "复制",
        confirmColor: "#1E85FF",
      });

      if (confirm) {
        let text = `${data?.customerName}-${constructionDetail?.constructionProjectName}-红杉树装饰：`;
        text += `${setting.webUrl
          }/customer/execution/${constructionPlanId}?encryptToken=${encodeURIComponent(
            res.encryptId
          )}`;

        Taro.setClipboardData({ data: text });
      }
    },
  });

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          planState == "complate" ? (
            <ByButton
              className="w-2/3"
              size="large"
              loading={loading}
              onClick={() => getEncryptId({ encryptId: constructionPlanId })}
            >
              客户分享
              <Text className="text-sm text-third">有效期3天</Text>
            </ByButton>
          ) : (
            <ByRow>
              {!isExtensionPending && (
                <ByCol span={4} className="mr-3">
                  <ByButton
                    type="error"
                    size="large"
                    variant="outline"
                    onClick={handleExtension.setTrue}
                  >
                    延期
                  </ByButton>
                </ByCol>
              )}

              <ByCol span={"auto"}>
                <ByButton size="large" onClick={handleComplete.setTrue}>
                  {planState == "unstarted" ? "开工" : "完工"}
                </ByButton>
              </ByCol>
            </ByRow>
          )
        }
      >
        <View className="flex-auto p-4">
          <Card>
            <ByRow>
              <ByCol span="auto">
                <View className="font-bold text-lg">{data?.customerName}</View>

                <View className="mt-2">
                  <ByIcon name="Location" size={24} />
                  <Text className="pl-1 text-third text-xs">
                    {data?.decorationFullAddress}
                  </Text>
                </View>
              </ByCol>

              <ByIcon name="Phone" size={40} className="text-primary" />
            </ByRow>
          </Card>

          <View className="mt-6 mb-3 text-third">开工信息</View>

          {planState == "unstarted" ? (
            <ByEmpty text="待开工" icon="Unstarted" />
          ) : (
            <Card>
              <ByRow>
                <ByCol span={6}>
                  <View className="text-third">计划开工</View>
                  <View className="mt-2">
                    <Moment
                      value={
                        constructionDetail?.planStartEditDate ||
                        constructionDetail?.planStartDate
                      }
                      placeholder="-"
                    />
                  </View>
                </ByCol>
                <ByCol span={6}>
                  <View className="text-third">实际开工</View>
                  <View className="mt-2">
                    <Moment
                      value={constructionDetail?.realStartDate}
                      placeholder="-"
                    />
                  </View>
                </ByCol>
              </ByRow>

              <View className="mt-6 mb-2 text-third">开工照片</View>
              <ByImageGroup
                showEmptyTip
                urls={constructionDetail?.formConstructionStartPlanPicList?.map(
                  (e) => e.picture!
                )}
              />

              <View className="mt-6 mb-2 text-third">开工工人照片</View>
              <ByImageGroup
                showEmptyTip
                urls={constructionDetail?.workerCompletedStartPics}
              />
            </Card>
          )}

          {planState == "complate" && (
            <ByCellGroup title="完工信息" className="mt-6">
              <ByRow>
                <ByCol span={5}>
                  <ByCell label="计划完工" vertical>
                    <Moment
                      value={
                        constructionDetail?.planFinishEditDate ||
                        constructionDetail?.planFinishDate
                      }
                      placeholder="-"
                    />
                  </ByCell>
                </ByCol>
                <ByCol span={7}>
                  <ByCell label="实际完工" vertical>
                    <Moment
                      value={constructionDetail?.realEndDate}
                      placeholder="-"
                    />

                    {isExtension && (
                      <ByText type="error" className="text-xs pl-2">
                        延期{constructionDetail!.extensionDate}天
                      </ByText>
                    )}
                  </ByCell>
                </ByCol>
              </ByRow>

              <ByCell label="完工照片" vertical>
                <ByImageGroup
                  showEmptyTip
                  urls={constructionDetail?.formConstructionFinishPlanPicList?.map(
                    (e) => e.picture!
                  )}
                />
              </ByCell>

              <ByCell label="完工工人照片" vertical>
                <ByImageGroup
                  showEmptyTip
                  urls={constructionDetail?.workerCompletedFinishPics}
                />
              </ByCell>
            </ByCellGroup>
          )}

          {extensionList.length > 0 && (
            <ByCellGroup title="延期申请" className="mt-6">
              <View className="py-2">
                {extensionList.map((item, index) => (
                  <>
                    {index > 0 && <Divider />}
                    <ExtensionRecordCard item={item} />
                  </>
                ))}
              </View>
            </ByCellGroup>
          )}
        </View>
      </Page>

      {/* 延期弹窗 */}
      {visibleExtension && (
        <PopupExtension
          source={constructionDetail!}
          intentCustomerId={intentCustomerId}
          isSkipHoliday={constructionDetail?.isSkipHoliday}
          onCancel={handleExtension.setFalse}
          onSuccess={refresh}
        />
      )}
      {/* 完成弹窗 */}
      {visibleCompleted && (
        <PopupCompleted
          isSwitch={isSwitch?.switch}
          planState={planState}
          source={constructionDetail!}
          customerName={data?.customerName}
          onCancel={handleComplete.setFalse}
          onSuccess={refresh}
        />
      )}
    </>
  );
};
